package com.fangmou.ing.publish.freemarker.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.fangmou.ing.publish.freemarker.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 插入文本命令，将标签包含的内容插入到指定位置（通过override、super联合实现）
 * 需指目标参照物、相对参照物位置（默认为插入参照物前）
 * @必传参数：target（目标参照物）
 * @可选参数：locate（相对参照物位置，取值范围：before、after）
 * @author kongdy
 */
public class InsertDirective implements TemplateDirectiveModel {

  public void execute(Environment env, Map params, TemplateModel[] loopVars,
      TemplateDirectiveBody body) throws TemplateException, IOException {
    
    String name = DirectiveUtils.getRequiredParam(params, "target");
    String locate = DirectiveUtils.getLocateParam(params);
    
    VirtualBody virb = new VirtualBody(body, env, locate);

    params.put("name", name);
    OverrideDirective over = new OverrideDirective();
    over.execute(env, params, loopVars, virb);
  }
  
  class VirtualBody implements TemplateDirectiveBody {
    Environment env;
    TemplateDirectiveBody body;
    String locate;

    public VirtualBody(TemplateDirectiveBody body, Environment env, String locate) {
      this.env = env;
      this.body = body;
      this.locate = locate;
    }

    public void render(Writer out) throws TemplateException, IOException {
      
      if(DirectiveUtils.LOCATE_BEFORE.equals(this.locate) && body!=null){
        body.render(out);
      }
      Map params = new HashMap();
      SuperDirective sup = new SuperDirective();
      sup.execute(env, params, null, body);
      
      if(DirectiveUtils.LOCATE_AFTER.equals(this.locate) && body!=null){
        body.render(out);
      }
    }

  }
}
